import DefaultImage from '@/asset/default-image.png';
import ErrorComp from '@/components/common/error-comp';
import ImageCarousel from '@/components/common/image-carousel';
import LeftToRightView from '@/components/common/motion/left-to-right-view';
import QueryImage from '@/components/common/query-image';
import AddRemoveCart from '@/components/user/add-remove-cart';
import UserCart from '@/components/user/user-cart';
import { getSession } from '@/lib/auth';
import { gorse } from '@/lib/gorse';
import { getCart } from '@/service/query/cart';
import { getShopById } from '@/service/query/shop';
import Link from 'next/link';
import { after } from 'next/server';
import { z } from 'zod';

export const metadata = {
  title: '商铺详情',
};

const paramSchema = z.object({
  id: z.coerce.number().int().positive(),
});

export default async function Page({
  params,
}: { params: Promise<{ id: string }> }) {
  const session = await getSession();
  if (!session?.user) return <ErrorComp message="用户未登录" />;

  const paramsRes = paramSchema.safeParse(await params);
  if (!paramsRes.success) return <ErrorComp message="参数错误" />;

  const { result, error } = await getShopById(paramsRes.data.id);
  if (error) return <ErrorComp message={error.message} />;

  const { result: cart, error: cartError } = await getCart(paramsRes.data.id);

  after(() =>
    gorse.insertFeedbacks([
      {
        itemId: paramsRes.data.id.toString(),
        userId: session.user.id,
        type: 'click',
      },
    ]),
  );

  return (
    <LeftToRightView>
      <div className="bg-transparent">
        <div className="relative top-5">
          <ImageCarousel imageKeys={result.imageKeys} />
        </div>
        <div className="bg-background shadow-lg relative z-10 rounded-t-3xl p-10 space-y-6">
          <div className="text-2xl font-bold">{result.name}</div>
          <div className="text-sm text-muted-foreground">
            {result.description}
          </div>
          <div className="flex justify-between  mb-10">
            <div className="text-lg font-bold">菜单</div>
            {cartError ? (
              <div>错误：{cartError.message}</div>
            ) : (
              <UserCart cart={cart} currentShop={result} />
            )}
          </div>
          <div className="mb-10 h-[1px] bg-muted-foreground/30" />
          <div className="space-y-12">
            {result.products.map((product) => (
              <div
                key={product.id}
                className="flex justify-between items-center gap-10 hover:bg-muted rounded-lg p-5 transition-colors"
              >
                <div className="flex gap-5">
                  <QueryImage
                    imageKey={product.imageKeys[0]}
                    defaultImage={DefaultImage}
                    wrapperClassName="rounded-lg w-40 h-20 shrink-0"
                    imgClassName="rounded-lg w-full h-full object-cover"
                  />
                  <div className="relative">
                    <Link href={`/detail-shop/product/${product.id}`}>
                      <div className="text-base font-bold">{product.name}</div>
                      <div className="text-xs text-muted-foreground line-clamp-2">
                        {product.description}
                      </div>
                      <div className="text-lg font-bold absolute bottom-0">
                        {product.price}元
                      </div>
                    </Link>
                  </div>
                </div>
                {cartError ? (
                  <div>无法获取购物车信息</div>
                ) : (
                  <AddRemoveCart
                    shopId={paramsRes.data.id}
                    productId={product.id}
                    count={cart[product.id.toString()] ?? 0}
                  />
                )}
              </div>
            ))}
          </div>
        </div>
      </div>
    </LeftToRightView>
  );
}
